package tmt.usercenter.web.configure.security.bean;

import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 作者：ThreeManTeam
 * 创建时间：2019-01-10 11:47
 */
public class MyCorsFilter extends CorsFilter {

    public MyCorsFilter() {
        super(new UrlBasedCorsConfigurationSource());
    }

    public MyCorsFilter(CorsConfigurationSource configSource) {
        super(configSource);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (!StringUtils.isEmpty(request.getHeader("Origin"))
                && !StringUtils.isEmpty(request.getHeader("host"))
                && !request.getHeader("origin").endsWith(request.getHeader("host"))) {
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        }
        filterChain.doFilter(request, response);
    }

}